<template>
	<view class="uni-numbox">
		<view class="uni-numbox-minus" :class="{'uni-numbox-disabled': disableSubtract}" @click="subtract">-</view>
		<input class="uni-numbox-value" type="number" :disabled="disabled" v-model="value" @blur="handleBlur">
		<view class="uni-numbox-plus" :class="{'uni-numbox-disabled': disableAdd}" @click="add">+</view>
	</view>
</template>
<script>
	export default {
		name: 'number-box',
		props: {
			id:{
				type:Number,
				default:0
			},
			value: {
				type: Number,
				default: 0
			},
			min: {
				type: Number,
				default: -Infinity
			},
			max: {
				type: Number,
				default: Infinity
			},
			step: {
				type: Number,
				default: 1
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			disableSubtract() {
				return this.value <= this.min
			},
			disableAdd() {
				return this.value >= this.max
			}
		},
		onUnload() {
			this.value = 0,
				this.step = 1,
				this.max = Infinity,
				this.min = -Infinity;
		},
		methods: {
			subtract(evt) {
				this._handleStep('subtract');
			},
			add(evt) {
				this._handleStep('add');
			},
			_handleStep(type) {
				let value = parseInt(this.value);
				if (type === 'subtract') {
					value -= this.step
				} else if (type === 'add') {
					value += this.step
				}
				if (value < this.min || value > this.max) {
					return
				}
				this.value = value
			},
			handleBlur(evt) {
				let value = parseInt(this.value);
				if (!value) {
					this.value = 0;
					return
				}
				value = +value;
				if (value > this.max) {
					value = this.max;
				} else if (value < this.min) {
					value = this.min
				}
				this.value = value
			}
		},
		watch: {
			value(val) {
				this.$emit('update', {id:this.id,value:val});
			}
		}
	}
</script>
<style>
	.uni-numbox {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		height: 40upx;
	}

	.uni-numbox-minus{
		margin-right: 15upx;
		margin-top: 7upx;
		width: 35upx;
		height: 35upx;
		line-height: 35upx;
		text-align: center;
		color: #45AA8C;
		border: 2upx solid #45AA8C;
		border-radius: 22upx;
	}
	.uni-numbox-plus {
		margin-left: 15upx;
		margin-top: 7upx;
		width: 35upx;
		height: 35upx;
		line-height: 35upx;
		text-align: center;
		color: #45AA8C;
		border: 1upx solid #45AA8C;
		border-radius: 22upx;
	}

	.uni-numbox-value {
		border: 1upx solid #45AA8C;
		width: 102upx;
		height: 40upx;
		text-align: center;
		color: #4B4B4B;
		border-radius:30upx;
		line-height: 40upx;
		font-size: 28upx;
	}

	.uni-numbox-disabled {
		color: #c1c3c9;
	}
</style>
